import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class demo_0501 {
    public static void main(String[] args) throws SQLException {

        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("123456");

        Connection connection = dataSource.getConnection();

        String sql = "select * from student where name = ?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1,"张三");

        ResultSet rusultSet =  preparedStatement.executeQuery();
        while (rusultSet.next()) {
            int id = rusultSet.getInt("id");
            String name = rusultSet.getString("name");
            System.out.println("id：" + id + " name：" + name);
        }

        rusultSet.close();
        preparedStatement.close();
        connection.close();
    }
    public static void main1(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        int id = scanner.nextInt();
        scanner.nextLine();
        String name = scanner.next();
        //1.创建 DataSource
        DataSource datasource = new MysqlDataSource();
        ((MysqlDataSource) datasource).setUrl("jdbc:mysql://127.0.0.1:3306/java?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) datasource).setUser("root");
        ((MysqlDataSource) datasource).setPassword("123456");

        //2.建立连接
        //选 Java.sql 下的 Connection
        //会抛异常
        Connection connection = datasource.getConnection();

        //3.构造 sql
        //String sql = "insert into student values(1,'张三')";
        //String sql = String.format("insert into student values(%d,'%s')", id, name);
//        String sql = "insert into student values(" + id + ", '"+ name + "')";
        String sql = "insert into student values(?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, id);
        statement.setString(2, name);
        //delete from student where id = 1


        //4.发给sql服务器, 执行sql
        //n表示影响的行数
        int n = statement.executeUpdate();
        System.out.println(n);

        //5.释放资源，关闭连接。  后获先释放
        statement.close();
        connection.close();
    }
}
